package com.loop.unclelend.ui.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.view.View
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.loop.unclelend.R
import com.loop.unclelend.databinding.UiPageApplyBinding
import com.loop.unclelend.pro.ProActivity
import com.loop.unclelend.ui.adapter.Adapter_Apply_Days
import com.loop.unclelend.ui.adapter.Adapter_Apply_Details
import com.loop.unclelend.ui.presenter.Pre_Apply
import com.loop.unclelend.ui.view.IView_Apply
import com.loop.unclelend.utils.DensityUtils
import com.loop.unclelend.utils.decoration.GridSpacingItemDecoration
import com.loop.unclelend.utils.decoration.LinearSpacingItemDecoration
import com.loop.unclelend.utils.event.UncleEventData
import com.loop.unclelend.utils.event.UncleEventHelper
import com.loop.unclelend.utils.event.UncleEventType
import com.loop.unclelend.utils.helper.TestAnalysisAddEvent
import org.json.JSONArray
import org.json.JSONObject
import java.math.BigDecimal

/**
 * UncleLend
 * @Author wwdeng
 * @CreateTime: 2024/9/25 19:21
 * @Annotation：申请贷款
 */
class Act_Apply: ProActivity(),IView_Apply {
    lateinit var binding: UiPageApplyBinding
    private var presenter: Pre_Apply? = null

    //老客申请金额刻度
    private var mScale = 0
    private var mMinProcess = 0//最小值

    //选择时间
    private var daysAdapter: Adapter_Apply_Days? = null
    //贷款明细
    private var detailsAdapter: Adapter_Apply_Details? = null

    companion object {
        private const val INTENT_KEY_AMOUNT = "defaultAmount"
        fun start(context: Context, amount: String) {
            val intent = Intent(context, Act_Apply::class.java)
            intent.putExtra(INTENT_KEY_AMOUNT, amount)
            context.startActivity(intent)
        }
    }

    override fun getUncleRootView(): View {
        binding = UiPageApplyBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initUncleView() {
        setUncleTitleBarVisibility(View.VISIBLE)
        setUncleTextTitle(getString(R.string.loan_apply_title))
        setUncleBackBtnRes(R.mipmap.icon_back)
        setUncleRightBtnRes(R.mipmap.icon_kefu)

        initUncleRefreshLayout()
        initDaysRecyclerView()
        initDetailsRecyclerView()
        binding.txtAmount.text = intent.extras!!.getString(INTENT_KEY_AMOUNT)
        binding.layoutContent.visibility = View.GONE
    }

    override fun initUncleListener() {
        //客服
        rootViewBinding.imgKefu.setOnClickListener {
            val eventRemark = "LoanApply Page"
            showUncleKefuDialog(eventRemark)
            UncleEventHelper.addUncleRequestEventAction(UncleEventType.CLICK.UNCLE_CLICK_CUSTOMER,eventRemark)
        }
        binding.seekBar.setOnSeekBarChangeListener(object : OnSeekBarChangeListener{
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                // 当进度改变时调用
                val showProcess = progress * mScale + mMinProcess
                binding.txtAmount.text = "$showProcess"
            }
            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                // 当用户开始触摸SeekBar（按下）时调用
            }
            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                // 当用户结束触摸SeekBar（抬手）时调用
                initUncleData()
            }
        })

        //提交
        binding.btnSubmit.setOnClickListener {
            showUncleLoading()
            presenter!!.requestCreateApplyOrderAction()
            UncleEventHelper.addUncleRequestEventAction(UncleEventType.CLICK.UNCLE_CLICK_LOAN_APPLY_SUBMIT)
        }
    }

    override fun initUncleData() {
        if (presenter == null){
            presenter = Pre_Apply(this)
        }
        showUncleLoading()
        presenter!!.requestApplyDataAction()
    }

    /* 初始化刷新 */
    private fun initUncleRefreshLayout() {
        //禁止加载
        binding.refreshLayout.setEnableLoadMore(false)
        binding.refreshLayout.setEnableAutoLoadMore(false)
        binding.refreshLayout.setOnRefreshListener {
            presenter!!.requestApplyDataAction()
        }
        binding.refreshLayout.setOnLoadMoreListener {
            binding.refreshLayout.finishLoadMore()
        }
    }

    /**
     * 选择days列表
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun initDaysRecyclerView(){
        binding.recyclerView.setHasFixedSize(true)
        binding.recyclerView.isNestedScrollingEnabled = false
        binding.recyclerView.isFocusableInTouchMode = false //不需要焦点
        val decoration = DensityUtils.dp2px(9f)
        binding.recyclerView.addItemDecoration(GridSpacingItemDecoration(3,decoration,false))
        val layoutManager = GridLayoutManager(getContext(),3)
        binding.recyclerView.layoutManager = layoutManager
        daysAdapter = Adapter_Apply_Days(binding.recyclerView)
        daysAdapter!!.setOnItemChildClickListener { _, _, position ->
            val item = this.daysAdapter!!.getItem(position)
            if (!item.optBoolean("isEnabled",true) || item.optBoolean("isSelect",false)){
                return@setOnItemChildClickListener
            }
            for (i in 0..<daysAdapter!!.itemCount){
                val model = daysAdapter!!.getItem(i)
                model.put("isSelect",false)
                if (i == position){
                    model.put("isSelect",true)
                }
            }
            daysAdapter!!.notifyDataSetChanged()

            //刷新数据
            initUncleData()
        }
        binding.recyclerView.adapter = daysAdapter
    }

    /**
     * 初始化明细列表
     */
    private fun initDetailsRecyclerView() {
        binding.rvDetails.setHasFixedSize(true)
        binding.rvDetails.isNestedScrollingEnabled = false
        binding.rvDetails.isFocusableInTouchMode = false //不需要焦点
        val decoration = DensityUtils.dp2px(16f)
        binding.rvDetails.addItemDecoration(LinearSpacingItemDecoration(0,0,0,decoration))
        binding.rvDetails.layoutManager = LinearLayoutManager(this)
        detailsAdapter = Adapter_Apply_Details(binding.rvDetails)
        binding.rvDetails.adapter = detailsAdapter!!
        binding.rvDetails.itemAnimator = DefaultItemAnimator()
        detailsAdapter!!.setOnItemChildClickListener{ _, childView, _ ->
            if (childView.id == R.id.itemLayout) {//切换item

            }
        }
    }

    /**
     * 获取贷款金额
     */
    override fun getApplyAmount(): String {
        return binding.txtAmount.text.toString()
    }

    /**
     * 获取贷款期限
     */
    override fun getApplyDays(): String {
        var days = ""
        if (daysAdapter!!.itemCount > 0){
            for (i in 0..<daysAdapter!!.itemCount){
                val item = daysAdapter!!.getItem(i)
                if (item.optBoolean("isSelect",false)){
                    days = item.optString("day")
                    break
                }
            }
        }
        return days
    }

    /**
     * 不可选择贷款额度
     */
    override fun showNotOptionalViews() {
        binding.layoutAmount.setBackgroundResource(R.mipmap.icon_loan_amount_bg)
        binding.seekBar.visibility = View.GONE
        binding.loanAmountLayout.visibility = View.GONE
    }

    /**
     * 允许选择贷款额度
     */
    override fun showOptionalViews(data: JSONObject) {
        binding.layoutAmount.setBackgroundResource(R.mipmap.icon_loan_apply_bg)
        binding.seekBar.visibility = View.VISIBLE
        binding.loanAmountLayout.visibility = View.VISIBLE

        val amount = BigDecimal(data.optString("amount")).stripTrailingZeros().toPlainString()
        mMinProcess = BigDecimal(data.optString("minAmount")).stripTrailingZeros().toPlainString().toInt()
        val maxAmount = BigDecimal(data.optString("maxAmount")).stripTrailingZeros().toPlainString()
        //颗粒度
        mScale = data.optInt("granularity")

        //设置最大值
        val maxProcess = (maxAmount.toInt() - mMinProcess) / mScale
        binding.seekBar.max = maxProcess
        //设置当前值
        val showAmount = (amount.toInt() - mMinProcess) / mScale
        binding.seekBar.progress = showAmount

        binding.txtMinAmount.text = "$mMinProcess"
        binding.txtMaxAmount.text = maxAmount
    }

    /**
     * 设置贷款期限
     */
    override fun showLoanDurationList(data: JSONObject) {
        if (daysAdapter!!.itemCount == 0){
            //默认天数
            val defaultDays = data.optString("days")
            val daysArray = data.optJSONArray("daysArray")
            val dayList = arrayListOf<JSONObject>()
            if (daysArray != null) {
                //如果daysArray中没有defaultDays，需要将defaultDays添加到daysArray列表中
                var isNeedAdd = true
                for (i in 0..<daysArray.length()){
                    if (daysArray.optString(i) == defaultDays){
                        isNeedAdd = false
                        break
                    }
                }
                if (isNeedAdd){
                    daysArray.put(0,defaultDays)
                }

                for (i in 0..<daysArray.length()){
                    val day = daysArray.optString(i)
                    val obj = JSONObject()
                    obj.put("day",day)
                    obj.put("isSelect",day == defaultDays)
                    obj.put("isEnabled",true)
                    dayList.add(obj)
                }
            } else {
                val obj = JSONObject()
                obj.put("day",defaultDays)
                obj.put("isSelect",true)
                obj.put("isEnabled",true)
                dayList.add(obj)
            }
            daysAdapter!!.data = dayList
        }
    }

    /**
     * 设置贷款明细
     */
    override fun showLoadDetailsList(data: JSONObject) {
        binding.layoutContent.visibility = View.VISIBLE
        //去掉末尾的0
        val amount = BigDecimal(data.optString("amount")).stripTrailingZeros().toPlainString()
        binding.txtAmount.text = amount

        //明细
        val array = data.optJSONArray("detailItemList")
        val dataList = arrayListOf<JSONObject>()
        if (array != null){
            for (i in 0..<array.length()){
                val item = array.optJSONObject(i)
                if (item.has("title") && item.optString("title") == "YES"){
                    dataList.add(item)
                }
            }
            for (i in 0..<dataList.size){
                val obj = dataList[i]
                val childArray = JSONArray()
                var isAddChild = false
                for (n in 0..<array.length()){
                    val item = array.optJSONObject(n)
                    if (obj.optString("showName") == item.optString("showName")){
                        isAddChild = true
                        continue
                    }
                    if (item.has("title") && item.optString("title") == "YES"){
                        isAddChild = false
                        continue
                    }
                    if (isAddChild){
                        childArray.put(item)
                    }
                }
                obj.put("childList",childArray)
            }
        }
        detailsAdapter!!.data = dataList
    }

    /**
     * 贷款申请成功
     */
    override fun showLoanApplySuccess() {
        //贷款申请成功 - 需要打点
        TestAnalysisAddEvent.addApplyEvent()
        publishEventData(UncleEventData(UncleEventData.TYPE.UNCLE_PROCESS_REFRESH))
        //进入SMS权限使用说明页面
        onIntent(Act_Apply_Wait::class.java)
        Handler(Looper.myLooper()!!).postDelayed({
            finish()
        },500)
    }

    /**
     * 申请失败 订单状态 或 申请状态 验证不通过，需要返回首页显示对应页面
     */
    override fun showLoanApplyFailed() {
        hideUncleLoading()
        finish()
    }

    override fun hideUncleLoading() {
        super.hideUncleLoading()
        binding.refreshLayout.finishRefresh()
    }

    override fun onStart() {
        super.onStart()
        UncleEventHelper.addUncleRequestEventAction(UncleEventType.PAGE.UNCLE_PAGE_LOAN_APPLY_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        UncleEventHelper.addUncleRequestEventAction(UncleEventType.PAGE.UNCLE_PAGE_LOAN_APPLY_END)
    }
}